<template>
    <div class="edu-page-warp">
        <InnerBreadcrumb v-model="indexKey" :path="breadPath" :show-back="true" />
        <div v-show="indexKey == 'main'">
            <condition-card label-width="120px" @reset="reset" @search="onSubmit">
                <el-col :span="8">
                    <el-form-item :label="$t('label.nowGrade')">
                        <el-date-picker
                            v-model="queryForm.grade"
                            :clearable="false"
                            :placeholder="$t('message.plzSelect')"
                            type="year"
                            value-format="yyyy"
                            style="width: 100%"
                            @change="handleGradeChanged"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('label.major')">
                        <el-select
                            v-model="queryForm.professionCode"
                            style="width:100%"
                            clearable
                            filterable
                        >
                            <el-option
                                v-for="(item, index) in options.major"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="考核地点">
                        <el-input v-model="queryForm.address" maxlength="50" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('message.status')">
                        <el-select
                            v-model="queryForm.status"
                            style="width:100%"
                            clearable
                            filterable
                        >
                            <el-option
                                v-for="(item, index) in options.status"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="考核时间">
                        <el-date-picker
                            v-model="queryForm.time"
                            :start-placeholder="$t('message.startTime')"
                            :end-placeholder="$t('message.endTime')"
                            type="datetimerange"
                            range-separator="至"
                        />
                    </el-form-item>
                </el-col>
            </condition-card>
            <el-card shadow="never">
                <div class="edu-page-title">专业选拔考核安排</div>
                <el-row style="margin-bottom:8px">
                    <el-col :span="24">
                        <el-button type="primary" class="float-right" @click="handleAdd">
                            {{ $t('message.add') }}
                        </el-button>
                    </el-col>
                </el-row>
                <edu-table ref="mainTable" :url="getUrl()" :order="false">
                    <el-table-column :label="$t('label.grade')" width="100" prop="grade" />
                    <el-table-column
                        :label="$t('label.major')"
                        width="200"
                        prop="professionName"
                        show-overflow-tooltip
                    />
                    <el-table-column label="考核场次" width="100" prop="number" />
                    <el-table-column
                        label="考核地点"
                        width="140"
                        prop="address"
                        show-overflow-tooltip
                    />
                    <el-table-column label="考核时间" width="320">
                        <template slot-scope="scope">
                            {{ getExamTime(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('message.status')" width="80">
                        <template slot-scope="scope">
                            <el-tag v-if="scope.row.status === '0'">
                                {{ getStatus(scope.row) }}
                            </el-tag>
                            <el-tag v-else-if="scope.row.status === '1'" type="success">
                                {{ getStatus(scope.row) }}
                            </el-tag>
                            <el-tag v-else type="danger">{{ getStatus(scope.row) }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="场次人数" width="100" prop="studentNumber" />
                    <el-table-column label="审批意见" prop="approveContent" show-overflow-tooltip />
                    <el-table-column :label="$t('label.operation')" width="180" fixed="right">
                        <template slot-scope="scope">
                            <el-button
                                v-if="scope.row.status === '0'"
                                type="text"
                                @click="handleCheck(scope.row)"
                            >
                                {{ $t('message.check') }}
                            </el-button>
                            <el-button
                                v-if="scope.row.status === '0' || scope.row.status === '2'"
                                type="text"
                                @click="handleEdit(scope.row)"
                            >
                                {{ $t('message.edit') }}
                            </el-button>
                            <el-button
                                v-if="scope.row.status === '0' || scope.row.status === '2'"
                                type="text"
                                @click="handleDelete(scope.row)"
                            >
                                {{ $t('message.delete') }}
                            </el-button>
                            <el-button type="text" @click="handleDetail(scope.row)">
                                {{ $t('message.detail') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </edu-table>
            </el-card>
        </div>
        <div v-if="indexKey !== 'main'">
            <el-card shadow="never">
                <el-form
                    ref="examPlanForm"
                    :model="examPlanForm"
                    :rules="examPlanFormRules"
                    label-suffix="："
                    label-position="right"
                    label-width="130px"
                >
                    <el-row>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')" prop="grade">
                                <el-date-picker
                                    v-model="examPlanForm.grade"
                                    :placeholder="$t('message.plzSelect')"
                                    :disabled="readOnly"
                                    type="year"
                                    value-format="yyyy"
                                    style="width: 100%"
                                    @change="handleFormGradeChanged"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.major')" prop="professionCode">
                                <el-select
                                    v-model="examPlanForm.professionCode"
                                    :disabled="readOnly"
                                    style="width:100%"
                                    clearable
                                    filterable
                                >
                                    <el-option
                                        v-for="(item, index) in options.formMajor"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="考核场次" prop="number">
                                <el-input-number
                                    :disabled="readOnly"
                                    v-model="examPlanForm.number"
                                    :min="1"
                                    :max="1000"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="考核开始时间" prop="startTime">
                                <el-date-picker
                                    :disabled="readOnly"
                                    v-model="examPlanForm.startTime"
                                    :placeholder="$t('message.plzSelect')"
                                    type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="考核结束时间" prop="endTime">
                                <el-date-picker
                                    :disabled="readOnly"
                                    v-model="examPlanForm.endTime"
                                    :placeholder="$t('message.plzSelect')"
                                    type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="考核人数" prop="studentNumber">
                                <el-input-number
                                    :disabled="readOnly"
                                    v-model="examPlanForm.studentNumber"
                                    :min="1"
                                    :max="1000"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="考核地点" prop="address">
                                <el-input
                                    v-model="examPlanForm.address"
                                    :disabled="readOnly"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="16">
                            <el-form-item label="考核说明">
                                <el-input
                                    :rows="4"
                                    :disabled="readOnly"
                                    v-model="examPlanForm.remark"
                                    type="textarea"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-row>
                    <div class="float-right">
                        <el-button @click="handleCancel">
                            {{ readOnly ? $t('message.return') : $t('message.cancel') }}
                        </el-button>
                        <el-button v-if="!readOnly" type="primary" @click="handleConfirm">
                            {{ $t('message.confirm') }}
                        </el-button>
                    </div>
                </el-row>
                <hr />
                <div class="edu-page-title">学生名单</div>
                <el-row style="margin-bottom:8px">
                    <el-col :span="24">
                        <el-button
                            v-if="!readOnly"
                            type="primary"
                            class="float-right"
                            @click="handleStudentNames"
                        >
                            生成名单
                        </el-button>
                    </el-col>
                </el-row>
                <edu-table :data="students">
                    <el-table-column :label="$t('label.stuCode')" prop="studentId" width="160" />
                    <el-table-column :label="$t('label.stuName')" prop="studentName" width="200" />
                    <el-table-column label="联系方式" prop="tel" />
                    <el-table-column v-if="!readOnly" :label="$t('label.operation')" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleDeleteStu(scope.row)">
                                {{ $t('message.delete') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </edu-table>
            </el-card>
        </div>
        <edu-dialog ref="checkDialog" :title="$t('message.check')" width="400px">
            <div>
                <el-form
                    ref="checkForm"
                    :model="checkForm"
                    label-suffix="："
                    label-position="right"
                    label-width="100px"
                >
                    <el-row>
                        <el-col>
                            <el-form-item label="审核说明">
                                <el-input
                                    :rows="4"
                                    v-model="checkForm.remark"
                                    type="textarea"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div slot="buttons">
                <el-button @click="handleDialogClose">
                    {{ $t('message.cancel') }}
                </el-button>
                <el-button type="danger" @click="handleDialogReject">
                    {{ $t('message.reject') }}
                </el-button>
                <el-button type="primary" @click="handleDialogPass">
                    {{ $t('message.pass') }}
                </el-button>
            </div>
        </edu-dialog>
    </div>
</template>
<script>
import * as APIs from 'common/src/api/preparatoryGraduation/enroll'
import { findCampusProfessionList } from 'common/src/api/culture/campusProfession'
export default {
    name: 'PreparatoryExamPlan',
    data() {
        return {
            defaultYear: new Date().getFullYear() - 1,
            readOnly: false,
            editId: null,
            checkId: null,
            students: null,
            queryForm: {
                grade: null,
                professionCode: null,
                address: null,
                status: null,
                time: []
            },
            examPlanForm: {
                grade: null,
                professionCode: null,
                number: 1,
                startTime: null,
                endTime: null,
                studentNumber: 1,
                address: null,
                remark: null
            },
            checkForm: {
                remark: null
            },
            options: {
                status: [],
                major: [],
                formMajor: []
            },
            indexKey: 'main',
            breadPath: {
                label: '专业选拔考核安排',
                key: 'main',
                children: [
                    {
                        key: 'add',
                        label: '新增'
                    },
                    {
                        key: 'detail',
                        label: '详情'
                    },
                    {
                        key: 'edit',
                        label: '编辑'
                    }
                ]
            },
            examPlanFormRules: {
                grade: [
                    {
                        required: true,
                        message: '请选择年级',
                        trigger: 'change'
                    }
                ],
                professionCode: [
                    {
                        required: true,
                        message: '请选择专业',
                        trigger: 'change'
                    }
                ],
                number: [
                    {
                        required: true,
                        message: '请输入考核场次',
                        trigger: 'change'
                    }
                ],
                startTime: [
                    {
                        required: true,
                        message: '请选择考核开始时间',
                        trigger: 'change'
                    }
                ],
                endTime: [
                    {
                        required: true,
                        message: '请选择考核结束时间',
                        trigger: 'change'
                    }
                ],
                studentNumber: [
                    {
                        required: true,
                        message: '请输入考核人数',
                        trigger: 'change'
                    }
                ],
                address: [
                    {
                        required: true,
                        message: '请输入考核地点',
                        trigger: 'change'
                    }
                ]
            }
        }
    },
    mounted() {
        this.queryForm.grade = this.defaultYear.toString()
        this.options.status.push({ label: '待审核', value: '0' })
        this.options.status.push({ label: '通过', value: '1' })
        this.options.status.push({ label: '驳回', value: '2' })
        this.onSubmit()
        this.handleGradeChanged(this.queryForm.grade)
    },
    methods: {
        reset() {
            this.queryForm.grade = this.defaultYear.toString()
            this.queryForm.professionCode = null
            this.queryForm.address = null
            this.queryForm.status = null
            this.queryForm.time = []
            this.onSubmit()
        },
        onSubmit() {
            let params = _.cloneDeep(this.queryForm)
            if (params.time !== null && params.time.length > 0) {
                params.startTimeStr = moment(params.time[0]).format('YYYY-MM-DD HH:mm:ss')
                params.endTimeStr = moment(params.time[1]).format('YYYY-MM-DD HH:mm:ss')
            }
            this.$refs.mainTable.search(params)
        },
        //处理筛选年级变化
        handleGradeChanged(val) {
            this.queryForm.professionCode = null
            this.getMajors(val, res => {
                this.options.major = res.data.list.map(item => {
                    return {
                        label: `${item.professionName}(${item.professionCode})`,
                        value: item.professionCode
                    }
                })
            })
        },
        //处理考核安排表单年级变化
        handleFormGradeChanged(val, clear = true) {
            if (clear) {
                this.examPlanForm.professionCode = null
            }
            this.getMajors(val, res => {
                this.options.formMajor = res.data.list.map(item => {
                    return {
                        label: `${item.professionName}(${item.professionCode})`,
                        value: item.professionCode
                    }
                })
            })
        },
        getMajors(val, fn) {
            findCampusProfessionList({
                grade: val,
                inUsed: '0',
                projId: '1',
                pageNum_: 1,
                pageSize_: 1000
            }).then(res => {
                if (res.code === 200 && typeof fn === 'function') {
                    fn(res)
                }
            })
        },
        getUrl() {
            return APIs.getExamPlanListPageURL()
        },
        getExamTime(row) {
            return `${row.startTime} 至 ${row.endTime}`
        },
        getStatus(row) {
            let item = this.options.status.find(item => item.value === row.status)
            return item ? item.label : null
        },
        clearExamPlanForm() {
            this.options.formMajor = []
            Object.keys(this.examPlanForm).forEach(key => {
                this.examPlanForm[key] = null
            })
            this.examPlanForm.studentNumber = 1
            this.examPlanForm.number = 1
            this.editId = null
            this.students = null
        },
        bindExamPlan(row) {
            Object.keys(this.examPlanForm).forEach(key => {
                if (row.hasOwnProperty(key)) {
                    this.examPlanForm[key] = key === 'grade' ? String(row[key]) : row[key]
                }
            })
            this.handleFormGradeChanged(row.grade, false)
            APIs.getStudentList({ id: row.id }).then(res => {
                if (res.code === 200) {
                    this.students = res.data
                }
            })
        },
        handleAdd() {
            this.indexKey = 'add'
            this.clearExamPlanForm()
            this.readOnly = false
        },
        handleEdit(row) {
            this.indexKey = 'edit'
            this.clearExamPlanForm()
            this.readOnly = false
            this.bindExamPlan(row)
            this.editId = row.id
        },
        handleDelete(row) {
            this.$delConfirm(this.$t('message.areYouSureDelete')).then(() => {
                APIs.deletePreparatoryExamPlan({ id: row.id }).then(res => {
                    if (res.code === 200) {
                        this.$message({
                            type: 'success',
                            message: this.$t('message.deleteSuccess')
                        })
                        this.onSubmit()
                    }
                })
            })
        },
        handleCheck(row) {
            this.checkId = row.id
            this.$refs.checkDialog.open()
            this.checkForm.remark = null
        },
        handleDetail(row) {
            this.indexKey = 'detail'
            this.clearExamPlanForm()
            this.readOnly = true
            this.bindExamPlan(row)
        },
        handleCancel() {
            this.indexKey = 'main'
        },
        handleConfirm() {
            this.$refs.examPlanForm.validate(valid => {
                if (valid) {
                    if (
                        new Date(this.examPlanForm.startTime) > new Date(this.examPlanForm.endTime)
                    ) {
                        this.$message({
                            type: 'warning',
                            message: '考核开始时间不能超过考核结束时间'
                        })
                        return
                    }
                    let data = _.cloneDeep(this.examPlanForm)
                    if (this.students !== null && this.students.length > 0) {
                        data.studentIds = this.students.map(item => item.studentId)
                    }
                    if (this.editId) {
                        data.id = this.editId
                        APIs.editPreparatoryExamPlan(data).then(res => {
                            if (res.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: this.$t('message.editSuccess')
                                })
                                this.indexKey = 'main'
                                this.onSubmit()
                            }
                        })
                    } else {
                        APIs.addPreparatoryExamPlan(data).then(res => {
                            if (res.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: this.$t('message.addSuccess')
                                })
                                this.indexKey = 'main'
                                this.onSubmit()
                            }
                        })
                    }
                }
            })
        },
        handleDialogClose() {
            this.$refs.checkDialog.close()
        },
        handleDialogPass() {
            APIs.preparatoryExamPlanPass({
                id: this.checkId,
                approveContent: this.checkForm.remark
            }).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '审批通过'
                    })
                    this.$refs.checkDialog.close()
                    this.onSubmit()
                }
            })
        },
        handleDialogReject() {
            APIs.preparatoryExamPlanReject({
                id: this.checkId,
                approveContent: this.checkForm.remark
            }).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '审批驳回'
                    })
                    this.$refs.checkDialog.close()
                    this.onSubmit()
                }
            })
        },
        handleStudentNames() {
            this.$refs.examPlanForm.validate(valid => {
                if (valid) {
                    APIs.generateStudent(this.examPlanForm).then(res => {
                        if (res.code === 200) {
                            this.students = res.data
                        }
                    })
                } else {
                    this.$message({
                        type: 'warning',
                        message: '有必填项未填'
                    })
                }
            })
        },
        handleDeleteStu(row) {
            this.$delConfirm(this.$t('message.areYouSureDelete')).then(() => {
                this.students = this.students.filter(stu => stu.studentId !== row.studentId)
            })
        }
    }
}
</script>
